/*
 * @Version: 1.0
 * @Autor: yuchang
 * @Date: 2024-01-12 18:09:20
 * @LastEditors: yangfumin
 * @LastEditTime: 2024-01-30 18:45:05
 * @Description:
 */
import confirm from '@/assets/Icon/confirm.png'
import magnifying from '@/assets/Icon/magnifying.png'
import removeImg from '@/assets/Icon/removeImg.png'
import sonIcon from '@/assets/Icon/sonIcon.png'
import topIcon from '@/assets/Icon/topIcon.png'
import { DeleteOutlined, MehOutlined, PlusCircleOutlined } from '@ant-design/icons'
import { Input, message, Modal, Tree } from 'antd'
import { connect } from 'dva'
import React from 'react'
import styles from './styles.less'
const { Search } = Input
const { DirectoryTree } = Tree

function mapStateToProps({ globalModel, campusOrgModel }) {
  return {
    globalModel: globalModel,
    campusOrgModel: campusOrgModel,
  }
}
@connect(mapStateToProps)
class TreeNode extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      inputValue: '', //输入框内容
      searchValue: '', //搜索内容
      isHideAdd: '', //是否展示添加按钮
      isHideDelete: '', //是否展示删除按钮
      NodeTreeItem: null,
      modalVisible: false, //弹窗确认
    }
    this.dataList = [] //所有组织列表
  }

  //渲染之前
  componentWillMount() {
    let { treeList } = this.props
    this.generateList(treeList)
  }
  //渲染之后
  componentDidMount() {}
  //卸载
  componentWillUnmount() {}

  //加载树形结构
  loop = (data) => {
    let { searchValue, NodeTreeItem } = this.state
    let { checkOrg } = this.props.campusOrgModel
    let info = data.map((item) => {
      let index = item.name.indexOf(searchValue)
      let beforeStr = item.name.substr(0, index)
      let afterStr = item.name.substr(index + searchValue.length)
      let title =
        index > -1 ? (
          <div className={styles.treeTitle}>
            <span>
              {beforeStr}
              <span style={{ color: '#f50' }}>{searchValue}</span>
              {afterStr}
            </span>
            {NodeTreeItem && item.id === checkOrg.key && (
              <>
                <div
                  style={{
                    alignSelf: 'center',
                    marginLeft: 10,
                    display: this.state.isHideAdd,
                    zIndex: 9,
                    float: 'right',
                  }}
                  onClick={this.handleAddSub}>
                  <PlusCircleOutlined style={{ marginRight: 5 }} />
                </div>
                <div
                  style={{
                    alignSelf: 'center',
                    marginLeft: 10,
                    display: this.state.isHideDelete,
                    zIndex: 9,
                    float: 'right',
                  }}
                  onClick={this.handleDeleteSub}>
                  <DeleteOutlined style={{ marginRight: 5 }} />
                </div>
              </>
            )}
          </div>
        ) : (
          <span>{item.name}</span>
        )
      if (item.children) {
        return {
          ...item,
          title: title,
          key: item.id,
          icon: (
            <img
              src={item.parentId == 0 ? topIcon : sonIcon}
              style={{ marginRight: 8, width: item.parentId == 0 ? '22px' : '16px' }}
            />
          ),
          children: this.loop(item.children),
          type: item.type,
          parentId: item.parentId,
          name: item.name,
        }
      }

      return {
        ...item,
        title,
        key: item.id,
        icon: (
          <img
            src={item?.parentId == 0 ? topIcon : sonIcon}
            style={{ marginRight: 8, width: item.parentId == 0 ? '22px' : '16px' }}
          />
        ),
        type: item.type,
        parentId: item.parentId,
        name: item.name,
      }
    })
    return info
  }
  //搜索
  searchFun = () => {
    let { treeList } = this.props
    let { inputValue } = this.state
    let expandedKeys = this.dataList
      .map((item) => {
        if (item.title.indexOf(inputValue) > -1) {
          return this.getParentKey(item.key, treeList)
        }
        return null
      })
      .filter((item, i, self) => item && self.indexOf(item) === i)
    this.setState({
      expandedKeys: expandedKeys,
      searchValue: inputValue,
      autoExpandParent: true,
    })
  }
  //处理树数据
  generateList = (data) => {
    for (let i = 0; i < data.length; i++) {
      let node = data[i]
      let { id, name } = node
      this.dataList.push({ key: id, title: name, icon: <MehOutlined /> })
      if (node.children) {
        this.generateList(node.children)
      }
    }
  }
  getParentKey = (key, tree) => {
    let parentKey
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i]
      if (node.children) {
        if (node.children.some((item) => item.id === key)) {
          parentKey = node.id
        } else if (this.getParentKey(key, node.children)) {
          parentKey = this.getParentKey(key, node.children)
        }
      }
    }
    return parentKey
  }

  //树结构选中
  onSelect = (Keys, info) => {
    this.props.dispatch({
      type: 'campusOrgModel/setCheckOrg',
      payload: info.selectedNodes[0],
    })
    this.props.dispatch({
      type: 'campusOrgModel/setUpdateVisible',
      payload: true,
    })
    const pos = info.node.pos.split('-').length - 1
    if (pos === 1) {
      this.setState({
        NodeTreeItem: {
          key: info.node.key,
          name: info.node.title,
          pos: pos,
          children: info.node.children,
        },
        isHideDelete: '',
      })
    } else {
      this.setState({
        NodeTreeItem: {
          key: info.node.key,
          name: info.node.title,
          pos: pos,
          children: info.node.children,
        },
        isHideDelete: '',
        isHideAdd: '',
      })
    }
    let { rightStatus } = this.props
    if (rightStatus) {
      rightStatus(2)
    }
  }

  onExpand = (expandedKeys, info) => {
    this.setState({
      NodeTreeItem: null,
      expandedKeys: expandedKeys,
      searchValue: '',
      autoExpandParent: false,
    })
  }

  //新增方法
  handleAddSub = () => {
    let { addVisible } = this.props
    if (addVisible) {
      addVisible()
    }
  }
  //删除
  handleDeleteSub = () => {
    this.setState({
      modalVisible: true,
    })
  }
  //关闭确认
  onClose = () => {
    this.setState({
      modalVisible: false,
    })
  }
  //确认删除
  onOk = () => {
    let { checkOrg } = this.props.campusOrgModel
    this.props.dispatch({
      type: 'campusOrgModel/deleteOrganizationEffects',
      payload: {
        params: checkOrg.key,
        callback: () => {
          let { getTree } = this.props
          if (getTree) getTree()
          this.setState({
            modalVisible: false,
          })
          message.success({
            content: '删除成功',
            style: {
              marginTop: '5vh',
            },
          })
        },
      },
    })
  }
  render() {
    let { treeList } = this.props
    let { expandedKeys, autoExpandParent, inputValue, modalVisible } = this.state
    let { checkOrg } = this.props.campusOrgModel
    return (
      <React.Fragment>
        <div className={styles.normal}>
          <Input
            placeholder="请输入组织搜索"
            value={inputValue}
            onChange={(event) => {
              this.setState({ inputValue: event.target.value })
            }}
            suffix={<img src={magnifying} className={styles.magnifyingImg} onClick={this.searchFun} />}
            style={{ marginBottom: '20px' }}
          />
          <DirectoryTree
            className={styles.treeData}
            expandedKeys={expandedKeys}
            autoExpandParent={autoExpandParent}
            onExpand={this.onExpand}
            onSelect={this.onSelect}
            treeData={this.loop(treeList)}
          />
          <Modal
            className={styles.modalBox}
            closable={false}
            width={407}
            onCancel={this.onClose}
            open={modalVisible}
            footer={null}>
            <div className={styles.addTitle}>
              <div></div>
              <img
                src={removeImg}
                alt=""
                style={{ width: '21px', height: '21px', cursor: 'pointer' }}
                onClick={this.onClose}
              />
            </div>
            <img src={confirm} alt="confirm" style={{ width: '40px' }} />
            <div className={styles.tips}>此操作不可逆，确定删除{checkOrg?.name}吗？</div>
            <div className={styles.modelFooter}>
              <div
                className={styles.footerBtn}
                onClick={this.onOk}
                style={{
                  background: 'linear-gradient(90deg, #68ecd8 0%, #29a6ff 80%)',
                  color: '#fff',
                }}>
                确认
              </div>
              <div
                className={styles.footerBtn}
                onClick={this.onClose}
                style={{ border: '1px solid rgba(41,57,77,0.15)' }}>
                取消
              </div>
            </div>
          </Modal>
        </div>
      </React.Fragment>
    )
  }
}
export default TreeNode
